package com.exp.security.config;

import com.exp.security.config.sms.SmsLoginConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

/**
 *
 * @author zhangxj
 * @date 2025/1/2
 * @Description
 */
@Configuration
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        String[] allowedPaths = { "/sms/code"};
        // 开启授权保护
        http.authorizeHttpRequests(authorize -> authorize
            // 验证码请求不需要认证
            .requestMatchers(allowedPaths).permitAll()
            .anyRequest().authenticated()
        )
        // 表单登录配置
        .formLogin( form -> form.successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler())
        )
        .httpBasic(Customizer.withDefaults());


        // 手机号验证码登录配置
        http.with(SmsLoginConfigurer.smsLogin(),
                sms -> sms.successProcessHandler(new MyAuthenticationSuccessHandler())
                        .failureProcessHandler(new MyAuthenticationFailureHandler())
        );

        // 关闭 CSRF 保护
        http.csrf(AbstractHttpConfigurer::disable);
        // 开启跨域
        http.cors(Customizer.withDefaults());
        return http.build();
    }
}
